# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pymysql
from django.contrib.auth.decorators import login_required
from django.db import connection
from django.http import HttpResponseRedirect, Http404, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.urls import reverse

from learning_logs.forms import TopicForm, EntryForm
from learning_logs.models import Topic, Entry


def index(request):
    """学习笔记的主页"""
    return render(request, 'learning_logs/index.html')


# def topics(request):
#     """Show all topics."""
#     topics = Topic.objects.order_by('date_append')
#     context = {'topics': topics}
#     return render(request, 'learning_logs/topics.html', context)

@login_required
def topics(request):
    """"显示所有主题"""
    topics1 = Topic.objects.filter(owner=request.user).order_by('date_append')
    # cur = connection.cursor()
    # cur.execute("insert into learning_logs_topic(owner_id,text,date_append) values ( 2,'game','2020-02-21 14:42')")

    pymysql_insert_test()
    context = {'topics': topics1}
    return render(request, 'learning_logs/topics.html', context)


# return JsonResponse({"status": "BS.200", "msg":" publish article success."})
# 测试pymysql用法，当然也可以直接使用orm，models类--表的映射
def pymysql_insert_test():
    print('insert test')
    conn = pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        database='guest',
        passwd='123456',
    )
    cur = conn.cursor()
    cur.execute(
        "insert into learning_logs_topic(owner_id,text,date_append) values ( 1,'testpymysql','2020-02-21 14:42')")
    conn.commit()  # 使用pymysql时不要忘了commit
    print('insert test2')


@login_required
def topic(request, topic_id):
    topic = Topic.objects.get(id=topic_id)
    # 确认请求的主题属于当前用户
    if topic.owner != request.user:
        raise Http404
    entries = topic.entry_set.order_by('date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)


@login_required
def new_topic(request):
    if request.method != 'POST':
        form = TopicForm()  # 第一次访问url模式learning_logs:new_topic时，是GET请求，转向new_topic.html，生成一个空表单（与Topic模型关联），让用户填写主题(
        # Topic.text)
    else:  # 点击提交表单按钮POST数据时，即填写完text进行第二次访问learning_logs:new_topic时，保存数据后转向learning_logs:topics
        # POST提交的数据，对数据进行处理
        form = TopicForm(request.POST)  # 使用用户输入的数据（它们存储在request.POST中）创建一个TopicForm
        if form.is_valid():
            new_topic = form.save(commit=False)  # 保存数据到数据库
            new_topic.owner = request.user
            new_topic.save()
            return HttpResponseRedirect(reverse('learning_logs:topics'))  # reversed获取页面topics的url
    context = {'form': form}
    return render(request, 'learning_logs/new_topic.html', context)


@login_required
def new_entry(request, topic_id):
    topic = Topic.objects.get(id=topic_id)
    if request.method != 'POST':
        form = EntryForm()
    else:
        form = EntryForm(data=request.POST)
        if form.is_valid():
            new_entry = form.save(commit=False)  # 只存储了条目内容text，单并未持久化保存到数据库
            new_entry.topic = topic  # 外键关联
            new_entry.save()  # 这次是真的保存到了数据库
            return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic.id]))

    context = {'form': form, 'topic': topic}
    return render(request, 'learning_logs/new_entry.html', context)


@login_required
def edit_entry(request, entry_id):
    entry = Entry.objects.get(id=entry_id)
    topic = entry.topic
    if topic.owner != request.user:
        raise Http404
    print(topic.id, topic.text, entry.topic, entry.text)
    if request.method != 'POST':
        form = EntryForm(instance=entry)
    else:
        form = EntryForm(instance=entry, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic.id]))

    context = {'form': form, 'entry': entry, 'topic': topic}
    return render(request, 'learning_logs/edit_entry.html', context)
